package org.example.thread5;

import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wangMaoXiong
 * @version 1.0
 * @date 2020/10/31 17:27
 */
public class MyThread6 extends Thread {
    //类成员变量，提供给多个线程中的实例进行数据共享
    private static int count = 9;
    //创建锁实例对象，类成员变量
    //如果 lock 不是静态成员变量，则 lock.lock() 相当于对象锁，只能对不同线程中的同一对象有效
    //相当于 synchronized(this)
    private static final Lock lock = new ReentrantLock();

    @Override
    public void run() {
        //执行内容前，先上锁，lock是类成员变量，所以对任何线程中的本类实例有效
        lock.lock();
        try {
            for (int i = 0; i < 3; i++) {
                count--;
                System.out.println(currentThread().getName() + "\ti=" + (i) + "\t count=" + count);
                Thread.sleep(500 + new Random().nextInt(1000));//稍作延迟，如果完全执行的太快，线程之间仍然会出现脏读的
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            //操作结束必须释放锁，否则此线程会一直独占资源，其余线程会饿死
            lock.unlock();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executorService = Executors.newCachedThreadPool();
        //使用线程池新开3个线程任务去对 MyThread 类中的 count 做自减操作
        for (int i = 0; i < 3; i++) {
            executorService.execute(new MyThread6());
        }
    }
    //pool-1-thread-1	i=0	 count=8
    //pool-1-thread-1	i=1	 count=7
    //pool-1-thread-1	i=2	 count=6
    //pool-1-thread-2	i=0	 count=5
    //pool-1-thread-2	i=1	 count=4
    //pool-1-thread-2	i=2	 count=3
    //pool-1-thread-3	i=0	 count=2
    //pool-1-thread-3	i=1	 count=1
    //pool-1-thread-3	i=2	 count=0
}